package com.hntx.joymusic.lsplayer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.hntx.joymusic.adapter.MyListAdapter;
import com.hntx.joymusic.bean.SocketBean;
import com.hntx.joymusic.bean.VideoBean;
import com.hntx.joymusic.bus.RxBus;
import com.hntx.joymusic.mediaplayer.StringUtils;
import com.hntx.joymusic.sytRetrofity.SytRetrofit;
import com.hntx.joymusic.util.LiveDataBus;
import com.hntx.joymusic.view.CenterRecyclerView;
import com.hntx.joymusic.view.focus.RecyclerViewSpacesItemDecoration;
import com.thunder.android.stb.util.log.Logger;
import com.thunder.android.stb.util.model.DownloadBean;
import com.thunder.ktv.player.helper.LyricsHelper;
import com.thunder.ktv.player.mediaplayer.callback.InitPlayerCallback;
import com.thunder.ktv.player.mediaplayer.callback.PlayerCreatedCallback;
import com.thunder.ktv.player.mediaplayer.callback.VodCallback;
import com.thunder.ktv.player.mediaplayer.listener.VodListener;
import com.thunder.ktv.player.mediaplayer.video.FactoryMediaPlayer;
import com.thunder.ktv.player.vod.VodReponseAction;
import com.thunder.ktv.player.vod.VodRequestAction;
import com.thunder.ktv.thunderextension.jni.thunderapi.TDFileUtils;
import com.hntx.joymusic.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.thunder.ktv.player.mediaplayer.video.IMediaPlayer;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LsPlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener,MyListAdapter.OnRightFocusChangeListener,
        MyListAdapter.OnRightClickListener, ViewTreeObserver.OnGlobalLayoutListener {

    private static final String TAG = "LsPlayerActivity";

    private static final int HIDE = 100, SHOW = 200 , REFRESH_SEEK_BAR_START = 1 , REFRESH_SEEK_BAR = -1,SEEK_VIEW_HIDE = 2;
    private int timeout = 8000;//按键自动隐藏时间
    private SurfaceView mPlayerView;
    private SeekBar seekBar;
    private RelativeLayout updateProgressBar;
    private ImageButton btn_play_pause;
    private TextView musicName, tv_time_total, tv_time_current, subtitle_text,
            seek_to_time, nextName, musicAuthor;
    private RelativeLayout playerControlBottomLayout;
    private ImageView paly_btn, load_img, forwardLeft, forwardRight,
            musicImg, musicCollect, origLyrics, musicReplay, musicNext, playMode, musicList,
            xingImg, xing_bg, lyrics_img;
    private CenterRecyclerView recycler;
    private List<VideoBean> videoBeanList = new ArrayList<>();
    private int startPosition;
    private String userId;
    private String firstUrl = null;
    private int nextPosition = 0;
    private String mName = null, authName = null, nextNameStr = null, songId;
    private MyListAdapter listAdapter;
    private LinearLayoutManager layoutManager;
    private String mBaseUrl = null;

    private int mAudioChannelMode=1;//原伴唱模式

    private IMediaPlayer mMediaPlayer;

    private boolean isInitPlayer = false;//雷石播放器是否初始化
    private boolean isSurfaceCreate = false;//Surfaceview是否创建完成


    private boolean  isTouchSeekBar=false;//SeekBar是否正在拖动

    private String videoSourcePath = Environment.getExternalStorageDirectory() + File.separator + "video/";

    private Handler myHandler = new Handler(this::handlerCallback);

    private static final int playerType = FactoryMediaPlayer.PLAYER_IJK;//雷石要求写PLAYER_IJK


    private int PLAY_MODE = 1;//顺序播放 1，单曲循环 2,随机播放 3

    private final int MSG_WHAT_TIME_CLOCK = 200300;
    private final int MSG_WHAT_SHOW_TOAST = 200500;
    private boolean limitOperate=false;
    private int audioChannelCount = 0;//音轨数量


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factoryvideo);
        /**21.06.24 麦克风相关以上*/
        registerMsg();
        initView();
        getInit();
        initData();
        //显示二维码
        showQR();
        //初始化播放器
        initPlayer(DeviceUtils.getMac(this));
    }




    private void initView() {
        lyrics_img = findViewById(R.id.lyrics_img);
        xingImg = findViewById(R.id.xing_img);
        xing_bg = findViewById(R.id.xing_bg);
        playerControlBottomLayout = findViewById(R.id.player_control_bottom_layout);
        paly_btn = findViewById(R.id.control_btn);
        seekBar = findViewById(R.id.seekBar);
        updateProgressBar = findViewById(R.id.update_progress);
        mPlayerView = findViewById(R.id.mPlayerView);
        btn_play_pause = findViewById(R.id.btn_play_pause);
        tv_time_total = findViewById(R.id.tv_time_total);
        tv_time_current = findViewById(R.id.tv_time_current);
        subtitle_text = findViewById(R.id.subtitle_text);
        load_img = findViewById(R.id.load_img);
        seek_to_time = findViewById(R.id.seek_to_time);



        recycler = findViewById(R.id.right_recycler);
        musicName = findViewById(R.id.music_name);
        nextName = findViewById(R.id.music_next_name);
        musicImg = findViewById(R.id.music_img);
        musicAuthor = findViewById(R.id.music_author);
        forwardLeft = findViewById(R.id.forward_left);
        forwardRight = findViewById(R.id.forward_right);
        musicCollect = findViewById(R.id.music_collect);
        origLyrics = findViewById(R.id.orig_lyrics);
        musicReplay = findViewById(R.id.music_replay);
        musicNext = findViewById(R.id.music_next);
        playMode = findViewById(R.id.play_mode);
        musicList = findViewById(R.id.music_list);
        //播放
        musicImg.setOnClickListener(v->{
        });
        //暂停继续
        paly_btn.setOnClickListener(v->{
            onVideoPause();
        });


        //重新播放
        musicReplay.setOnClickListener(v->{
            if (mMediaPlayer.isPaused()){
                onVideoPause();
                mMediaPlayer.seek(1.0f * 0);
            }else {
                mMediaPlayer.seek(1.0f * 0);
            }
        });
        forwardLeft.setOnClickListener(this);
        forwardRight.setOnClickListener(this);
        musicCollect.setOnClickListener(this);
        origLyrics.setOnClickListener(this);
//        musicReplay.setOnClickListener(this);
        musicNext.setOnClickListener(this);
        playMode.setOnClickListener(this);
        musicList.setOnClickListener(this);



        mPlayerView.getHolder().addCallback(this);



        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    tv_time_total.setText(" / "+millsecToString(i));
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isTouchSeekBar=true;
                Log.e(TAG, "onStartTrackingTouch: " + "触碰");
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isTouchSeekBar=false;
                int max = seekBar.getMax();
                //播放进度
                mMediaPlayer.seek(1.0f * seekBar.getProgress() / max);
            }
        }
        );
    }

    private void getInit() {
        videoBeanList = getIntent().getParcelableArrayListExtra("video_bean_list");
        startPosition = getIntent().getIntExtra("start_position", 0);
        firstUrl = getIntent().getStringExtra("firstUrl");
//        firstUrl ="http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8";
//      firstUrl="http://112.115.0.136:8090/202108/LSKTV/202112/20211206/90000001000000023604022153399302/90000001000000023604022153399302.m3u8?playType=vod&startProgramDate=1638952681071&expiredTime=600&checkKey=f936f5d10fd899af1f8583ab92e9fac1&userId=0010039901049500164574FF4C692042&stbNo=0010039901049500164574FF4C692042";
        userId = getIntent().getStringExtra("userId");
        if (videoBeanList != null)
            if (videoBeanList.size() > 0 && videoBeanList.size() > startPosition) {
                mName = videoBeanList.get(startPosition).getSongName();
                songId = videoBeanList.get(startPosition).getSongId();
                authName = videoBeanList.get(startPosition).getSinger();
                nextPosition = startPosition + 1;
                if (videoBeanList.size() > 1)
                    nextNameStr = videoBeanList.get(nextPosition).getSongName();
                else
                    nextNameStr = videoBeanList.get(startPosition).getSongName();
            }
    }

    private void initData() {
        mBaseUrl = getCacheDir().getAbsolutePath() + File.separator;
        Animation translateAnimation = AnimationUtils.loadAnimation(this, R.anim.load_anim);
        if (load_img != null) {
            load_img.setAnimation(translateAnimation);
            load_img.startAnimation(translateAnimation);
        }
        listAdapter = new MyListAdapter(this);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(listAdapter);
        listAdapter.addRightFocusChangeListener(this);
        listAdapter.addRightClickListener(this);
        recycler.addItemDecoration(new RecyclerViewSpacesItemDecoration(6));
        listAdapter.setData(videoBeanList);
        recycler.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    /**
     * 显示二维码
     */
    private void showQR() {
        Glide.with(this).asGif().load(R.mipmap.qr_k_bg).into(xing_bg);
        DisplayMetrics metric = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            getWindowManager().getDefaultDisplay().getRealMetrics(metric);
        }
        int height = metric.heightPixels; // 高度（PX）
        Observable<String> qrbase64 = SytRetrofit.getInstance().getQR(userId, height);
        if (qrbase64 != null)
            qrbase64.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            Log.e(TAG, "onNext: 二维码请求成功" );
                            showQRcode(s);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
//                            Toast.makeText(LsPlayerActivity.this,"二维码请求失败",Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "onError: 二维码请求失败" );
                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
    }

    /**
     * 初始化雷石播放器
     * @param snCode
     */
    private void initPlayer(String snCode) {
        isInitPlayer = true;
        FactoryMediaPlayer.getInstance().setLogLevel(5);
        FactoryMediaPlayer.getInstance().setHttpTimeout(60, 60, 60);
        //初始化播放器
        FactoryMediaPlayer.getInstance().initPlayer(this, playerType
                , snCode, new VodCallback() {
                    @Override
                    public void onStartUpComplete(VodListener vodListener) {

                    }

                    @Override
                    public void onAction(VodRequestAction vodRequestAction) {

                    }

                    @Override
                    public void onActionComplete(VodReponseAction vodReponseAction) {//学完测试。

                    }
                }, new InitPlayerCallback() {
                    @Override
                    public void onComplete() {
                        Log.e(TAG, "Sdk初始化成功");
                        getMediaPlayer();
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG, "onError: " + s);
                    }

                    @Override
                    public void reInitComplete() {
                        Log.e(TAG, "reInitComplete: ");
                    }
                });

        FactoryMediaPlayer.getInstance().setVgaOperateCodeChangeListener((s, l) -> {
            Log.d(TAG, "onVgaCodeChangeListener: " + s + "...." + l);
        });
        //歌词下载
//        LyricsHelper.getInstance().loadLyricsNewRules(getApplicationContext());
    }

    private void getMediaPlayer() {
        new Thread(() -> {
            //⼦线程创建播放器实例，切记回调也在⼦线程中。
            mMediaPlayer = FactoryMediaPlayer.getInstance().createPlayer(0, new PlayerCreatedCallback() {
                @Override
                public void onError(int i, String s) {
                    Log.e(TAG, "onError: " + s);
                }
            }, false);
            isInitPlayer = false;
            myHandler.sendEmptyMessage(REFRESH_SEEK_BAR_START);
        }).start();
    }

    /**
     * 播放视频
     * @param url 视频链接或雷石id
     * @param name 视频名称
     */
    private void playVideo(String url,String name) {
        Log.e(TAG, "playVideo: "+url);
        if (url==null){
            return;
        }
        IMediaPlayer.OnPreparedListener mPreparedListener = mp -> {
            Log.i(TAG, "onPrepared DecoderID = " + mp.getDecoderID());
            mp.start();//播放开始
            showSeekbar(false);
            limitOperate = true;
        };
        try {
            if (mMediaPlayer == null) {
                Log.e(TAG, "mPlayer is null.");
                return;
            }
            mMediaPlayer.reset();
            //设置资源准备加载监听回调
            mMediaPlayer.setOnPreparedListener(mPreparedListener);
            //设置播放完成回调
            mMediaPlayer.setOnCompletionListener(iMediaPlayer -> {
                nextMusic();
            });
            //设置播放出错回调
            mMediaPlayer.setOnErrorListener((iMediaPlayer, i, i1) -> {
                Log.e(TAG, String.format("mPlayer OnError i:%d   i1:%d", i, i1));
                return false;
            });
            //设置播放中回调，可以在此设置先默认1为原唱，2为伴唱。
            mMediaPlayer.setOnVideoRunningListener(iMediaPlayer -> {
                iMediaPlayer.setVolume(50);
                seekBar.setMax((int) iMediaPlayer.getDuration());
                audioChannelCount = getAudioStreamCount();
                if (audioChannelCount > 1) {
                    mMediaPlayer.selectAudioStream(mAudioChannelMode);
                } else {
                    mMediaPlayer.setAudioChannelMode(mAudioChannelMode);
                }
            });
            //快进回调
            mMediaPlayer.setOnSeekCompleteListener(iMediaPlayer -> {
            });
            //⽇志打印
            mMediaPlayer.setOnInfoListener((iMediaPlayer, i, i1) -> {

            });
            //缓存下载⽬录
            mMediaPlayer.setOnCacheDownloadListener((filepath, mediaFileName, mediaFileLength) -> {
                Log.d(TAG, "downloaded! filepath:" + filepath +
                        ",mediaFileName:" + mediaFileName + ",filelength:" + mediaFileLength);
                String dstFilePath = "/sdcard/" + mediaFileName;
                try {
                    String cmd = "cp -f " + filepath + " " + dstFilePath;
                    Process p = Runtime.getRuntime().exec(cmd);
                    p.waitFor();
                    TDFileUtils.fileTruncate(dstFilePath, mediaFileLength);
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.warn(filepath + " mv to " + dstFilePath + "failed!");
                    return;
                }
            });
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("musicno", url); //歌曲编号
                jsonObject.put("is265", "0");//视频编码是否是265
                jsonObject.put("resolution", "480");//分辨率
                jsonObject.put("ls", "0");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            final DownloadBean bean = new DownloadBean(name, url, videoSourcePath);//创建边下载边播实例
            bean.playWithDownload = false;//设置是否边下边播
            if (!url.startsWith("http")){
                mMediaPlayer.setDataSource(jsonObject.toString(), bean);//设置播放源
            }else{
                mMediaPlayer.setDataSource(url);//设置播放源
            }
            mMediaPlayer.prepareAsync();//异步加载播放源
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void onVideoPause() {
        if (mMediaPlayer==null){
            return;
        }
        //onVideoPause 暂停和继续播放视频
        if (mMediaPlayer.isPaused()) {
            btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
            mMediaPlayer.resume();
            paly_btn.setImageResource(R.drawable.player_control_playing_sel);
            if (!myHandler.hasMessages(REFRESH_SEEK_BAR)){
                myHandler.sendEmptyMessageAtTime(REFRESH_SEEK_BAR,1000);
            }
        }else {
            btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
            btn_play_pause.setVisibility(View.VISIBLE);
            mMediaPlayer.pause();
            paly_btn.setImageResource(R.drawable.player_control_pause_sel);
            if (myHandler.hasMessages(REFRESH_SEEK_BAR)){
                myHandler.removeMessages(REFRESH_SEEK_BAR);
            }
        }
    }

    /**
     * 重新播放
     * @param view
     */
    public void onViderAgain(View view) {
        if (mMediaPlayer.isPaused()){
            onVideoPause();
            mMediaPlayer.seek(1.0f * 0);
        }else {
            mMediaPlayer.seek(1.0f * 0);
        }
    }

    /**
     * 切换音频通道模式默认1为原唱，2为伴唱。
     */
    public void changeAudioChannelMode(){
        mAudioChannelMode=mAudioChannelMode==1?2:1;
        if (mAudioChannelMode != 1) {
            origLyrics.setImageResource(R.drawable.music_channel_sel1);
            ToastUtils.showLongToast("已切换到伴唱");
        } else {
            origLyrics.setImageResource(R.drawable.music_channel_sel);
            ToastUtils.showLongToast("已切换到原唱");
        }
        if (audioChannelCount > 1) {
            mMediaPlayer.selectAudioStream(mAudioChannelMode);
        } else {
            mMediaPlayer.setAudioChannelMode(mAudioChannelMode);
        }
    }
    private long mExitTime = 0;

    /**
     * 按键控制
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction()!=KeyEvent.ACTION_DOWN){
            return super.dispatchKeyEvent(event);
        }
        switch (event.getKeyCode()){
            case KeyEvent.KEYCODE_DPAD_DOWN:
                boolean isflag = false;
                if (!limitOperate) return true;
                myHandler.sendEmptyMessage(SEEK_VIEW_HIDE);
                myHandler.sendEmptyMessage(SHOW);
                if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                    View focusViewDown = getCurrentFocus();
                    if (focusViewDown != null)
                        if (focusViewDown.getId() == R.id.seekBar || focusViewDown.getId() == R.id.forward_left) {
                            paly_btn.requestFocus();
                            isflag = true;
                        } else if (focusViewDown.getId() == R.id.item) {
                            seekBar.requestFocus();
                            isflag = true;
                        }
                }
                return isflag;
            case KeyEvent.KEYCODE_DPAD_UP:
                boolean flag = false;
                if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                    View focusViewUp = getCurrentFocus();
                    if (focusViewUp != null)
                        if (focusViewUp.getId() == R.id.control_btn) {
                            seekBar.requestFocus();
                            flag = true;
                        }
                } else {
                    myHandler.sendEmptyMessage(SEEK_VIEW_HIDE);
                    myHandler.sendEmptyMessage(SHOW);
                }
                return flag;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (!limitOperate) return true;
                if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                    myHandler.sendEmptyMessage(SHOW);
                    View focusViewRight = getCurrentFocus();
                    if (focusViewRight != null)
                        if (focusViewRight.getId() == R.id.seekBar) {
                           onClick(forwardRight);
                            return true;
                        }
                } else {
                    if (mMediaPlayer != null) {
                        seekTo(seekBar.getProgress(), 5000);
                        onClick(forwardRight);
                    }
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (!limitOperate) return true;
                if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                    myHandler.sendEmptyMessage(SHOW);
                    View focusViewLeft = getCurrentFocus();
                    if (focusViewLeft != null)
                        if (focusViewLeft.getId() == R.id.seekBar) {
                            onClick(forwardLeft);
                            return true;
                        }
                } else {
                    if (mMediaPlayer != null) {
                        seekTo(seekBar.getProgress(), -5000);
                        onClick(forwardLeft);
                    }
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                if (!limitOperate) return true;
                myHandler.sendMessage(myHandler.obtainMessage(SHOW,false));
                View view = getCurrentFocus();
                if (seek_to_time.getVisibility() == View.VISIBLE) {
                    seek_to_time.setVisibility(View.GONE);
                }
                if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
                    updateProgressBar.setVisibility(View.GONE);
                }
                if (view == null || view.getId() == R.id.seekBar || view.getId() == R.id.btn_play_pause) {
                    if (mMediaPlayer != null) {
                        if (mMediaPlayer.isPlaying()&&!mMediaPlayer.isPaused()) {
                            pauseVisible();
                        } else {
                                btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
                                myHandler.sendEmptyMessage(HIDE);
                        }
                        onVideoPause();
                    }
                }
                break;
            case KeyEvent.KEYCODE_SPACE:
            case KeyEvent.KEYCODE_BACK:
                if (recycler.getVisibility() == View.VISIBLE) {
                    recycler.setVisibility(View.GONE);
                    return true;
                }
                //按返回隐藏播放菜单栏
                if (playerControlBottomLayout.getVisibility() == View.VISIBLE){
                    myHandler.sendEmptyMessage(HIDE);
                }
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出播放", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                    return true;
                } else {
                    exit();
//                            if (player != null) {
//                                player.onPause();
//                            }
//                            Log.d(TAG, "退出的地方，记录一下");
////                            String path2 = MediaRecordUtils.stopMediaRecord();
//                            if (mExitDialog == null)
//                                mExitDialog = new ExitDialog(this, new ExitDialog
//                                .onBtnClickListener() {
//                                    @Override
//                                    public void onSure(String path) {
//                                        exit();
//                                    }
//
//                                    @Override
//                                    public void onExit() {
//                                        if (player != null) {
//                                            player.onResume();
//                                        }
//                                    }
//                                }, null, null, null, null);
////                            mExitDialog.setPath(path2);
//                            mExitDialog.show();
//                            Log.d(TAG, "退出的地方，记录一下 展示");


//                            Log.d(TAG, "退出的地方，记录一下");
//                            String path2 = MediaRecordUtils.stopMediaRecord();
//                            if (mExitDialog == null)
//                                mExitDialog = new ExitDialog(this, new ExitDialog
//                                .onBtnClickListener() {
//                                    @Override
//                                    public void onSure(String path) {
////                                        Intent intent = new Intent(VideoPlayerPageActivity
// .this, AudioRecordAc.class);
////                                        intent.putExtra("path", path);
////                                        startActivity(intent);
//                                        exit();
//                                    }
//
//                                    @Override
//                                    public void onExit() {
////                                        startUpdateFile(path2);
//                                        createUploadUrl(path2);
////                                        exit();
//                                    }
//                                }, "退出", "上传录音", null, null);
//                            mExitDialog.setPath(path2);
//                            mExitDialog.show();
//                            Log.d(TAG, "退出的地方，记录一下 展示");
                }
                return true;

            case KeyEvent.KEYCODE_HOME:
                return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forward_right:
                //快进处理
                if (mMediaPlayer != null) {
                    if (mMediaPlayer.isPaused()){
                        onVideoPause();
                    }
                    float seek=(seekBar.getProgress()+5000f)/seekBar.getMax();
                    mMediaPlayer.seek(seek);
                }
                Toast.makeText(LsPlayerActivity.this, "快进", Toast.LENGTH_SHORT).show();
                break;
            case R.id.forward_left:
            //快退处理
                if (mMediaPlayer != null) {
                    if (mMediaPlayer.isPaused()){
                        onVideoPause();
                    }
                    float seek=(seekBar.getProgress()-5000f)/seekBar.getMax();
                    mMediaPlayer.seek(seek);
                 }
                Toast.makeText(LsPlayerActivity.this, "后退", Toast.LENGTH_SHORT).show();
                break;
            case R.id.music_collect:
                //提交收藏接口
                if (musicCollect.isSelected()) {
                    musicCollect.setSelected(false);
                } else {
                    musicCollect.setSelected(true);
                }
                collectPost();
                break;
            case R.id.orig_lyrics://快进
                changeAudioChannelMode();
                break;
            case R.id.music_next://切歌
                nextMusic();
                break;
            case R.id.music_list:
                //目前不清楚功能，应该是列表选择
                if (recycler.getVisibility() == View.VISIBLE) {
                    recycler.setVisibility(View.GONE);
                } else {
                    recycler.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.play_mode://切换播放模式
                PLAY_MODE++;
                switch (PLAY_MODE) {
                    case 1:
                        playMode.setImageResource(R.drawable.play_mode_sel);
                        break;
                    case 2:
                        playMode.setImageResource(R.drawable.play_mode_sel1);
                        break;
                    case 3:
                        playMode.setImageResource(R.drawable.play_mode_sel2);
                        break;
                    default:
                        PLAY_MODE = 1;
                        playMode.setImageResource(R.drawable.play_mode_sel);
                        break;
                }
                break;

            default:
                break;
        }
    }

    /**
     * 显示更换播放按钮图标
     */
    public void pauseVisible() {
        btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
        btn_play_pause.setVisibility(View.VISIBLE);
    }
    protected void exit() {
        myHandler.removeCallbacksAndMessages(null);
        LiveDataBus.getInstance().send("main", 10001);
        finish();
        overridePendingTransition(0, 0);
    }
    public void collectPost() {
        Observable<JsonObject> ob = SytRetrofit.getInstance()
                .postCollect(videoBeanList.get(startPosition).getSongId(),
                        userId, "1", "collect");
        if (ob != null)
            ob.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<JsonObject>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(JsonObject jsonObject) {
                            Log.d("sss", jsonObject.toString());
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
    }
    /**
     *  隐藏播放进度时间
     */
    private void hideSeekText() {
        if (seek_to_time != null && seek_to_time.getVisibility() == View.VISIBLE) {
            seek_to_time.setVisibility(View.GONE);
        }
    }
    /**
     *  是否播放中
     * @return
     */
    private boolean isPlaying(){
        if (mMediaPlayer==null){
            return false;
        }
        return mMediaPlayer.isPlaying()&&!mMediaPlayer.isPaused();
    }

    /**
     * 隐藏播放 进度
     */
    private void hideSeekbar() {
            if (isPlaying()) {
                playerControlBottomLayout.setVisibility(View.GONE);
                btn_play_pause.setVisibility(View.GONE);
                recycler.setVisibility(View.GONE);
            }
    }

    /**
     * 显示播放进度与操作按钮
      * @param sb 是否自动隐藏
     */
    private void showSeekbar(boolean sb) {
        playerControlBottomLayout.setVisibility(View.VISIBLE);
        if (mMediaPlayer != null) {
            if (!isPlaying()) {
                btn_play_pause.setVisibility(View.VISIBLE);
            }
        }
        if (sb){
            return;
        }
            if (myHandler.hasMessages(HIDE)){
                myHandler.removeMessages(HIDE);
            }

            myHandler.sendEmptyMessageDelayed(HIDE, timeout);
    }

    private final CompositeDisposable disposables = new CompositeDisposable();

    /**
     * 手机点歌相关监听
     */
    private void registerMsg() {
        disposables.add(RxBus.getInstance()
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
                    SocketBean bean = (SocketBean) object;
                    if ("order".equals(((SocketBean) object).getAction())) {
                        if (bean.getContent() != null && bean.getContent().size() > 0)
                            demandPlay(bean.getContent().get(0));
                    } else if ("list".equals(((SocketBean) object).getAction())) {
                        if (bean.getContent() != null && bean.getContent().size() > 0) {
                            videoBeanList.addAll(bean.getContent());
                            listAdapter.setData(videoBeanList);
                        }
                    } else if ("delete".equals(((SocketBean) object).getAction())) {
                        int pos = -1;
                        String songId = bean.getContent().get(0).getSongId();
                        for (int i = 0; i < videoBeanList.size(); i++) {
                            if (songId.equals(videoBeanList.get(i).getSongId())) pos = i;
                        }
                        if (pos == -1) return;
                        deleteSongCommit(pos);
                        videoBeanList.remove(pos);
                        isFocus = true;
                        isDel = true;
                        delPos = pos;
                        listAdapter.setData(videoBeanList);
//                    if (videoBeanList.size() == 0) {
//                        recycler.setVisibility(View.GONE);
//                    }
                    }
                }));

        disposables.add(RxBus.getInstance("playmsg")
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
//                    SocketBean bean = (SocketBean) object;
                    String action = object.toString();
                    Log.d("服务器消息：", "播放页面：" + action);
                    switch (action) {
//                        case "order":
//                            if (bean.getContent() != null && bean.getContent().size() > 0)
//                                demandPlay(bean.getContent().get(0));
//                            break;
                        case "vol_up":
                            dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent
                            .KEYCODE_VOLUME_UP));
//                            if (mAudioManager != null) {
//                                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
//                                        AudioManager.ADJUST_RAISE, 0);
//                            }
                            break;
                        case "vol_down":
                            dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent
                            .KEYCODE_VOLUME_DOWN));
//                            if (mAudioManager != null) {
//                                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
//                                        AudioManager.ADJUST_LOWER, 0);
//                            }
                            break;
                        case "mic_up":
//                            int curVolume = mMic.getVolume();
//                            mMic.setVolume(curVolume + 1);
                            break;
                        case "mic_down":
//                            int curVolumes = mMic.getVolume();
//                            mMic.setVolume(curVolumes - 1);
                            break;
                        case "ptoggle":
                            dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent
                                    .KEYCODE_DPAD_CENTER));
                            break;
                        case "ctoggle":
//                            switchLrics();
                            break;
                        case "reset":
                            if (mMediaPlayer.isPaused()){
                                onVideoPause();
                                mMediaPlayer.seek(1.0f * 0);
                            }else {
                                mMediaPlayer.seek(1.0f * 0);
                            }
                            break;
//                        case "delete":
//                            int pos = -1;
//                            String songId = bean.getContent().get(0).getSongId();
//                            for (int i = 0; i < videoBeanList.size(); i++) {
//                                if (songId.equals(videoBeanList.get(i).getSongId())) pos = i;
//                            }
//                            if (pos == -1) return;
//                            deleteSongCommit(pos);
//                            videoBeanList.remove(pos);
//                            isFocus = true;
//                            isDel = true;
//                            delPos = pos;
//                            listAdapter.setData(videoBeanList);
////                    if (videoBeanList.size() == 0) {
////                        recycler.setVisibility(View.GONE);
////                    }
//                            break;
//                        case "list":
//                            if (bean.getContent() != null && bean.getContent().size() > 0) {
//                                videoBeanList.addAll(bean.getContent());
//                                listAdapter.setData(videoBeanList);
//                            }
//                            break;
                        case "next":
                            nextMusic();
                            break;
                        case "listtop":
                            break;
                        default:
                            break;
                    }
                }));
    }

    /**
     * 取消手机点歌相关监听
     */
    private void destroyMpush() {
        if (disposables != null && disposables.size() > 0)
            disposables.clear();
    }
    private void demandPlay(VideoBean bean) {
        limitOperate = false;
        String path = bean.getCres();
        mName = bean.getSongName();
        songId = bean.getSongId();
        videoBeanList.add(bean);
        listAdapter.setData(videoBeanList);
        playVideo(path,mName);
    }

    /**
     * 显示二维码
     * @param xingurl base64二维码图片
     */
    void showQRcode(String xingurl) {
        if (TextUtils.isEmpty(xingurl)) return;
        byte[] decode = Base64.decode(xingurl.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        xingImg.setImageBitmap(bitmap);
        xingImg.setVisibility(View.VISIBLE);
        xing_bg.setVisibility(View.VISIBLE);
    }

    void hideQRcode() {
        xingImg.setVisibility(View.GONE);
        xing_bg.setVisibility(View.GONE);
    }

    /**
     * 切换下一首
     */
    private void nextMusic(){
        if (videoBeanList != null && videoBeanList.size() > 0) {
            limitOperate = false;
            int nextp = nextPosition;
            if (PLAY_MODE == 1) {
                nextPosition++;
                if (nextPosition >= videoBeanList.size()) {
                    nextPosition = 0;
                }
                startPosition = nextp;
            } else if (PLAY_MODE == 3) {
                nextPosition = new Random().nextInt(videoBeanList.size());
                startPosition = nextp;
            } else {
                nextPosition = startPosition;
            }
            if (videoBeanList.size() == 1) {
                startPosition = 0;
                nextPosition = 0;
            }
            String path = videoBeanList.get(startPosition).getSongRes();
            //改为测试地址
//            String path = pathi + videoBeanList.get(0).getSongRes();
            mName = videoBeanList.get(startPosition).getSongName();
            songId = videoBeanList.get(startPosition).getSongId();
            nextNameStr = videoBeanList.get(nextPosition).getSongName();
            authName = videoBeanList.get(startPosition).getSinger();
            String musicId = videoBeanList.get(startPosition).getCres();
            if (mMediaPlayer==null){
                return;
            }
            playVideo(musicId,mName);

        }else {
            limitOperate = true;
        }
    }

    /**
     * 显示歌曲播放进度
     * @param currentTime 歌曲总时长 毫秒
     * @param seekTime 当前进度 毫秒
     */
    private void seekTo(int currentTime, int seekTime) {
        StringBuilder sb = new StringBuilder();
        sb.append("(").append(StringUtils.generateTime(currentTime)).append(')');
        if (seekTime > 0) {
            sb.append("+" + seekTime / 1000f);
        } else {
            sb.append(seekTime / 1000f);
        }
        seek_to_time.setText(sb.toString());
        if (seek_to_time.getVisibility() != View.VISIBLE) {
            seek_to_time.setVisibility(View.VISIBLE);
        }
        myHandler.removeMessages(SEEK_VIEW_HIDE);
        myHandler.sendEmptyMessageDelayed(SEEK_VIEW_HIDE, 2000);
    }
    private boolean handlerCallback(Message msg) {
        switch (msg.what){
            case HIDE:
                hideSeekbar();
                break;
            case SHOW:
                boolean show = false;
                if (Boolean.TRUE.equals(msg.obj)){
                    show = true;
                }
                showSeekbar(show);
                break;
            case REFRESH_SEEK_BAR_START:
                if (isSurfaceCreate && !isInitPlayer && mMediaPlayer != null) {
                    Log.e(TAG, "开始设置播放器");
                    mMediaPlayer.setSurface(mPlayerView.getHolder().getSurface());//设置显⽰视图
                    if (!TextUtils.isEmpty(firstUrl)){
                        playVideo(firstUrl,mName);
                    }
                    myHandler.sendEmptyMessage(REFRESH_SEEK_BAR);
                }
                break;
            case SEEK_VIEW_HIDE:
                hideSeekText();
                break;
            case REFRESH_SEEK_BAR:
                refreshSeekBar();
                myHandler.sendEmptyMessageDelayed(REFRESH_SEEK_BAR,1000);
                break;
        }

        return true;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        isSurfaceCreate = true;
        myHandler.sendEmptyMessage(REFRESH_SEEK_BAR_START);
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        isSurfaceCreate = false;
    }

    /**
     * 刷新歌曲信息及进度条信息
     */
    private void refreshSeekBar(){
        //手指是否正在拖动进度条
        if (isTouchSeekBar){
            return;
        }
        musicName.setText(mName);
        musicAuthor.setText(authName);
        nextName.setText("下一首：" + nextNameStr);

        tv_time_current.setText(millsecToString(mMediaPlayer.getCurPosition()));
        tv_time_total.setText(" / " +millsecToString(mMediaPlayer.getDuration()));
        seekBar.setProgress((int) mMediaPlayer.getCurPosition());
    }

    /**
     * 将毫秒转为String
     * @param ms
     * @return
     */
    private static String millsecToString(long ms) {
        if (ms < 1000) {
            return "00:00";
        }

        String result = "";
        int s = Math.round(ms / 1000f);
        int m = s / 60;
        s = s % 60;
        int h = m / 60;
        m = m % 60;

        if (h > 0) {
            result += h + ":";
            if (m > 0) {
                if (m > 9) {
                    result += m + ":";
                } else {
                    result += "0" + m + ":";
                }
            }
        } else {
            if (m > 9) {
                result += m + ":";
            } else {
                result += "0" + m + ":";
            }
        }

        if (s > 9) {
            result += s;
        } else {
            result += "0" + s;
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        if (mMediaPlayer!=null){
            mMediaPlayer.stop();
        }
        destroyMpush();
        if (myHandler.hasMessages(-1)){
            myHandler.removeMessages(-1);
        }
        super.onDestroy();
    }


    @Override
    public void onRightFocusChange(View view, boolean flag, int pos) {
        if (flag) {
            recycler.smoothToCenter(pos);
        }
    }
    private boolean isFocus = false, isDel = false;
    private int delPos = 0;
    @Override
    public void onRightClick(View view, int pos) {
        switch (view.getId()) {
            case R.id.delete_m:
                deleteSongCommit(pos);
                videoBeanList.remove(pos);
                isFocus = true;
                isDel = true;
                delPos = pos;
                listAdapter.setData(videoBeanList);
                if (videoBeanList.size() == 0) {
                    recycler.setVisibility(View.GONE);
                }
                break;
            case R.id.start_play:
                startPosition = pos;
                if (PLAY_MODE == 1) {
                    nextPosition=pos+1;
                    if (nextPosition >= videoBeanList.size()) {
                        nextPosition = 0;
                    }
                } else if (PLAY_MODE == 3) {
                    nextPosition = new Random().nextInt(videoBeanList.size());
                }
                String path = videoBeanList.get(startPosition).getSongRes();
                //改为测试地址
//            String path = pathi + videoBeanList.get(0).getSongRes();
                mName = videoBeanList.get(startPosition).getSongName();
                songId = videoBeanList.get(startPosition).getSongId();
                nextNameStr = videoBeanList.get(nextPosition).getSongName();
                authName = videoBeanList.get(startPosition).getSinger();
                String musicId = videoBeanList.get(startPosition).getCres();
                if (mMediaPlayer==null){
                    return;
                }
                playVideo(musicId,mName);
                break;
        }
    }

    @Override
    public void onGlobalLayout() {
        if (videoBeanList.size() > 0)
            if (recycler.getVisibility() == View.VISIBLE && isFocus) {
                isFocus = false;
                if (isDel) {
                    isDel = false;
                    if (videoBeanList.size() > 0) {
                        if (videoBeanList.size() > delPos)
                            recycler.getLayoutManager().findViewByPosition(delPos).findViewById(R.id.delete_m).requestFocus();
                        else {
                            recycler.getLayoutManager().findViewByPosition(videoBeanList.size() - 1).findViewById(R.id.delete_m).requestFocus();
                        }
                    }
                } else
                    recycler.getLayoutManager().findViewByPosition(startPosition).findViewById(R.id.start_play).requestFocus();
            }
    }
    private void deleteSongCommit(int pos) {
        Observable<JsonObject> ob =
                SytRetrofit.getInstance().postDel(videoBeanList.get(pos).getSongId(), userId, "1");
        ob.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JsonObject jsonObject) {
                        Log.d("sss", jsonObject.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private int getAudioStreamCount() {
        return mMediaPlayer.getAudioStreamCount();
    }

}
